<template>
  <p-layout-header class="home-header">
    <div class="home-header-left">
      <!--导航菜单样式 1、默认-->
      <template v-if="system.sysNavType === 1">
        <!-- <p-sys-nav>
          <div class="system-nav-icon">
            <svg-icon type="cell" />
          </div>
        </p-sys-nav> -->

        <div class="system-logo">
          <!-- <img v-show="systemLogo" :src="systemLogo" alt="logo" /> -->
          <svg-icon class="logo-icon" type="logo" />
          <span>{{ systemName }}</span>
        </div>
      </template>

      <!--导航菜单样式 2-->
      <template v-else-if="system.sysNavType === 2">
        <div class="system-logo system-nav2">
          <img v-show="systemLogo" :src="systemLogo" alt="logo" />
          <span>{{ systemName }}</span>
        </div>

        <p-sys-nav2 />
      </template>
    </div>

    <div class="home-header-right">
      <div
        v-for="(item, index) of customButtonList"
        :key="index"
        class="button"
        @click="customButtonNav(item)"
      >
        <template v-if="item.badge">
          <p-badge dot :count="item.count">
            <p-icon class="button-icon" :type="item.icon" />
          </p-badge>
        </template>
        <p-icon v-else class="button-icon" :type="item.icon" />
        <span class="button-label">{{ item[customButtonTitleField] }}</span>
      </div>

      <p-dropdown overlay-class-name="header-dropdown">
        <div class="button">
          <p-avatar class="button-icon" :src="avatar" :size="24" />
          <p-icon type="down" />
        </div>

        <div slot="overlay">
          <div class="base-info">
            <p-avatar class="button-icon" :src="avatar" :size="24" />

            <ul class="user-info">
              <li class="company-name">
                {{ companyName }}
              </li>
              <li class="user-name">
                {{ username }}
              </li>
            </ul>
          </div>

          <p-menu :selectable="false" @click="handler">
            <p-menu-item v-if="isMultiTenant" key="switchTenant">
              <p-gt-icon type="switchuser" />{{ locale.switchTenant }}
            </p-menu-item>
            <!-- <p-menu-item key="goAuth">
              <a target="_self" rel="noopener noreferrer" href="/auth">
                <p-icon type="undo" />{{ locale.backPortal }}
              </a>
            </p-menu-item>
            <p-menu-item key="userCenter">
              <router-link to="/userCenter">
                <p-icon type="user" />{{ locale.userCenter }}
              </router-link>
            </p-menu-item>
            <p-menu-item key="language">
              <p-gt-icon type="translate" />{{
                locale.switchLanguage(language)
              }}
            </p-menu-item> -->
            <p-menu-item key="logout">
              <p-icon type="logout" />{{ locale.exit }}
            </p-menu-item>
          </p-menu>
        </div>
      </p-dropdown>
    </div>

    <!--消息通知-->
    <p-message-notify
      v-if="messageNotifyEnable"
      :visible.sync="notifyVisible"
      @updateUnreadTotal="notifyUnreadUpdate"
    />

    <!--切换租户-->
    <p-modal
      v-if="isMultiTenant && switchTenantVisible"
      v-model="switchTenantVisible"
      title="切换租户"
      :width="368"
      :footer="null"
    >
      <select-tenant />
    </p-modal>
  </p-layout-header>
</template>

<script>
import { mapState, mapGetters } from 'vuex';
import system from '@/config/system';
import avatarDefault from '@/assets/images/avatar.png';
import { isURL } from '@/utils';
import { getTenantList } from '@/api/login';
import SelectTenant from '@/views/login/components/select-tenant';

// 右上角 通知 按钮配置
const NOTIFY_BUTTON_CONFIG = {
  label: '通知',
  englishLabel: 'notify',
  type: 'notify',
  icon: 'bell',
  badge: true,
  count: 0, // 控制小红点
};
// 右上角 帮助 按钮配置
const HELPER_BUTTON_CONFIG = {
  label: '帮助',
  englishLabel: 'help',
  icon: 'question-circle',
  url: '',
  openNew: true,
};

export default {
  name: 'HomeHeader',
  components: {
    SelectTenant,
  },
  data() {
    return {
      system,

      // 启用站内信
      messageNotifyEnable: system.messageNotify,

      // 自定义按钮列表
      customButtonList: [],

      notifyVisible: false,

      switchTenantVisible: false,
    };
  },
  computed: {
    ...mapState({
      tenantList: (state) => state.user.tenantList,
    }),
    // ...mapGetters(['language', 'systemName']),
    ...mapGetters(['language']),
    systemName() {
      return '产销通（LTC）平台';
    },

    // 当前用户属于多个租户
    isMultiTenant() {
      return this.tenantList.length > 1;
    },

    locale() {
      return require(`./locale/${this.language}`).default;
    },

    systemLogo() {
      try {
        const { sysList } = this.$store.state.poros;
        const currentSystem = sysList.find(
          (item) => item.systemCode === system.code
        );

        return currentSystem.icon;
      } catch (e) {
        return '';
      }
    },

    customButtonTitleField() {
      return this.language === 'zh_CN' ? 'label' : 'englishLabel';
    },

    avatar() {
      return this.$store.state.user.avatar || avatarDefault;
    },
    username() {
      return this.$store.state.user.name;
    },
    companyName() {
      return this.$store.state.user?.userInfo.companyName;
    },
  },
  watch: {
    systemName: {
      handler(val) {
        if (val) {
          document.title = val;
        }
      },
      immediate: true,
    },
  },

  created() {
    this.getTenantList();
    this.customButtonInit();
  },
  methods: {
    // 获取租户列表
    getTenantList() {
      // 数据存在时 无需重复获取 - 属于多租户的用户 从 开发登录页 登录进入时
      if (this.tenantList.length > 0) {
        return;
      }

      getTenantList()
        .then((res) => {
          if (res.code === 0) {
            this.$store.commit('setTenantList', res.data);
          } else {
            throw new Error(res.msg);
          }
        })
        .catch((err) => {
          console.error(err.message);
        });
    },

    // 自定义按钮 初始化
    customButtonInit() {
      this.customButtonList = [
        // HELPER_BUTTON_CONFIG, // 帮助按钮
      ];

      // 通知 - 开启站内信时需要
      if (this.messageNotifyEnable) {
        this.customButtonList.unshift(NOTIFY_BUTTON_CONFIG);
      }

      // config 中配置的 添加到最前面
      this.customButtonList.unshift(...(system.customButton || []));
    },
    // 自定义按钮点击
    customButtonNav({ type, url, openNew }) {
      // 通知
      if (type === 'notify') {
        this.openNotify();
        return;
      }

      // 其他
      if (!url) {
        this.$message.warning(this.locale.noLinkTips);
        return;
      }

      if (openNew) {
        window.open(url, '_blank');
      } else {
        if (isURL(url)) {
          location.href = url;
        } else {
          this.$router.push(url);
        }
      }
    },

    // 站内信
    openNotify() {
      this.notifyVisible = true;
    },
    notifyUnreadUpdate(unreadTotal) {
      // 更新未读信息数量，控制 小红点
      this.$set(NOTIFY_BUTTON_CONFIG, 'count', unreadTotal);
    },

    // 头像 下拉菜单 点击 处理
    handler({ key }) {
      switch (key) {
        case 'switchTenant':
          this.switchTenantVisible = true;
          break;
        case 'language':
          this.$store.dispatch('switchLanguage');
          break;
        case 'logout':
          this.logout();
          break;
      }
    },

    // 退出登录
    logout() {
      this.$confirm('是否确认退出登录？')
        .then(() => {
          this.$store.dispatch('logout');
        })
        .catch(() => {
          // this.$message.info('已取消');
        });
    },
  },
};
</script>

<style lang="less" scoped>
.logo-icon {
  height: 28px !important;
  width: 28px !important;
  margin-right: 8px;
}
.home-header {
  justify-content: space-between;

  &-left,
  &-right {
    display: flex;
  }

  &-left {
    .system-nav-icon {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 48px;
      height: 48px;
      background: @sys-menu-bgcolor;
      cursor: pointer;
      color: @sys-cell-color;
      font-size: 20px;

      .svg-icon {
        margin-right: 0;
      }
    }

    .system-logo {
      display: flex;
      align-items: center;
      margin-left: 20px;
      white-space: nowrap;

      span {
        font-size: 16px;
        font-weight: bold;
        color: @sys-menu-bgcolor;
      }

      &.system-nav2 {
        display: flex;
        width: 200px;
        margin-left: 0;
        padding-left: 20px;

        span {
          flex: 1;
          width: 0;
          white-space: nowrap;
          text-overflow: ellipsis;
          overflow: hidden;
        }
      }

      img {
        max-height: 30px;
        margin-right: 6px;
      }
    }
  }

  &-right {
    align-items: center;

    .button {
      display: flex;
      align-items: center;
      margin-right: 20px;
      cursor: pointer;
      transition: color 0.3s;

      &:hover {
        color: @primary-color;
      }

      &-icon {
        font-size: 14px;

        &.poros-avatar {
          margin-right: 4px;
        }
      }

      &-label {
        margin-left: 5px;
      }
    }
  }
}
</style>
<style lang="less">
.header-dropdown {
  width: 160px;
  padding-bottom: 10px;
  box-shadow: 0 2px 6px 0 rgba(4, 12, 44, 0.25);
  border-radius: 4px;
  border: 1px solid #e6e7ea;
  background-color: #fff;

  .base-info {
    display: flex;
    align-items: center;
    padding: 10px 8px;
    border-bottom: 1px solid #f0f1f3;

    .user-info {
      flex: 1;
      width: 0;
      margin-left: 10px;
      margin-bottom: 0;

      li {
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
    }
  }

  .poros-menu {
    border-right: none;

    &-item {
      height: 30px;
      line-height: 30px;
      margin-top: 0;
      margin-bottom: 0 !important;

      &:hover {
        background: #f2f3f4;
      }
    }
  }
}
</style>